package com.phf.vhr.utils;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;

/**
 * MybatisPlus 代码生成工具类
 *
 * @program: vhr-master
 * @description:
 * @author: Peng houfu
 * @create: 2021-09-24 16:07
 **/

public class CodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        Properties jdbcProperties = new Properties();
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties");
        try {
            jdbcProperties.load(is);
        } catch (IOException e) {
            throw new MybatisPlusException("load jdbc.properties error.");
        }

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        System.out.println(projectPath);
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setOpen(false);
        gc.setAuthor("phf");
        gc.setEntityName("%sDO");
        gc.setServiceName("%sService");
        gc.setFileOverride(true);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(jdbcProperties.getProperty("mysql.url"));
        dsc.setDriverName(jdbcProperties.getProperty("mysql.driver.name"));
        dsc.setUsername(jdbcProperties.getProperty("mysql.username"));
        dsc.setPassword(jdbcProperties.getProperty("mysql.password"));
        if (!Boolean.parseBoolean(jdbcProperties.getProperty("mysql.tinyint.boolean"))) {
            dsc.setTypeConvert(new MySqlTypeConvert() {
                @Override
                public IColumnType processTypeConvert(GlobalConfig config, String fieldType) {
                    String t = fieldType.toLowerCase();
                    if (t.contains("tinyint(1)")) {
                        return DbColumnType.INTEGER;
                    }
                    return super.processTypeConvert(config, fieldType);
                }
            });
        }
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //模块名
        pc.setParent("com.phf.vhr");
        pc.setEntity("model.entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        mpg.setPackageInfo(pc);
        
//        
        // 注入自定义配置，可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setController(null);
        mpg.setTemplate(templateConfig);
        
        //调整entity生成目录
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();

        //调整 xml 生成目录
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath+ "/vhr-mapper/src/main/resources/mapper/" + tableInfo.getXmlName() + StringPool.DOT_XML;
            }
        });

        //生成实体DO类
        focList.add(new FileOutConfig("/templates/entity.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/vhr-model/src/main/java/com/phf/vhr/model/entity/" + tableInfo.getEntityName() + ".java";
            }
        });

        //调整service生成目录
        focList.add(new FileOutConfig("/templates/service.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath+ "/vhr-service/src/main/java/com/phf/vhr/service/" + tableInfo.getServiceName() + ".java";
            }
        });
        //调整serviceImpl生成目录
        focList.add(new FileOutConfig("/templates/serviceImpl.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath+ "/vhr-service/src/main/java/com/phf/vhr/service/impl/" + tableInfo.getServiceImplName() + ".java";
            }
        });
        //调整mapper生成目录
        focList.add(new FileOutConfig("/templates/mapper.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath+ "/vhr-mapper/src/main/java/com/phf/vhr/mapper/" + tableInfo.getMapperName() + ".java";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new VelocityTemplateEngine());
        
        mpg.execute();
    }
}
